package com.acceptable.qucun.generic.util;

import javax.servlet.ServletInputStream;
import java.io.IOException;

public class StringFormatUtil {

    private final static String[] localDateTime =
            {"2[0-9]{3}-[0-9]{2}-[0-9]{2}_[0-9]{2}-[0-9]{2}-[0-9]{2}_",
            "2[0-9]{3}-[0-9]{2}-[0-9]{2}T[0-9]{2}-[0-9]{2}-[0-9]{2}_"};

    /**
     *  判断字符串是否为空 含空串 长度为0
     * @param str 字符串本身
     * @return 为null或空串时 返回true
     */
    public static boolean isEmpty(String str){
        return str == null || "".equals(str);
    }

    /**
     *  首字母大写 含判空处理
     * @param origin 源字符串
     * @return 首字母大写的字符串
     */
    public static String capitalToUpperCase(String origin){
        if(isEmpty(origin))
            return "";
        StringBuilder dest = new StringBuilder(origin);
        dest.setCharAt(0, Character.toUpperCase(origin.charAt(0)));
        return dest.toString();
    }

    /**
     *  首字母小写 含判空处理
     * @param origin 源字符串
     * @return 首字母小写的字符串
     */
    public static String capitalToLowerCase(String origin){
        if(isEmpty(origin))
            return "";
        StringBuilder dest = new StringBuilder(origin);
        dest.setCharAt(0, Character.toLowerCase(origin.charAt(0)));
        return dest.toString();
    }

    /**
     *  小写单词下划线连接 转为 小驼峰
     *  含判空处理
     * @param origin 源字符串
     * @return 小驼峰格式字符串
     */
    public static String underlineToLowerCamel(String origin){
        if(isEmpty(origin))
            return "";
        if(!origin.contains("_"))
            return origin;
        String[] wordList = origin.split("_");
        StringBuilder dest = new StringBuilder();
        for (int i = 0; i < wordList.length; i++){
            dest.append(capitalToUpperCase(wordList[i]));
        }
        return dest.toString();
    }

    /**
     *  提取ServletInputStream中数据转为字符串
     * @param in 数据流
     * @return 提取后的字符串
     */
    public static String createFromServletInputStream(ServletInputStream in){
        byte[] buffer = new byte[1024];
        StringBuilder dataStr = new StringBuilder();
        try {
            while (!in.isFinished()){
                in.read(buffer);
                dataStr.append(new String(buffer).trim());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return dataStr.toString();
    }

    /**
     *  清空符合LocalDateTime格式的子串
     */
    public static String clearDate(String str){
        String res = str;
        for (String re: localDateTime){
            res = str.replaceAll(re,"");
            if (!str.equals(res)){
                break;
            }
        }
        return res;
    }
}
